import { asyncRoutes, constantRoutes } from '@/router'
import { getAuth } from '@/utils/auth'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// 判断路由权限的方法
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function hasPermissionId(ids, route) {
  if (route.meta && route.meta.id) {
    return ids.some(id => {
      return route.meta.id == id
    })
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

// 筛选路由的方法
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export function filterAsyncRoutesById(routes, ids) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermissionId(ids, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutesById(tmp.children, ids)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      // 调用过滤路由方法
      if (getAuth() && JSON.parse(getAuth()).length) {
        const authArr = JSON.parse(getAuth())[0].concat(JSON.parse(getAuth())[1])
        accessedRoutes = filterAsyncRoutesById(
          filterAsyncRoutes(asyncRoutes, roles),
          authArr
        )
        // console.log(getAuth());
        // console.log(accessedRoutes);
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
